QEMU := "../../qemu-build/riscv64-softmmu/qemu-system-riscv64"
# machine, supervisor, user, echo1, echo2
SERIAL_FLAGS := "-serial /dev/pts/0 -serial /dev/pts/1 -serial /dev/pts/1 -serial tcp::23334,server,nowait -serial tcp:localhost:23334"

TARGET := "riscv64gc-unknown-none-elf"
MODE := "release"
OBJDUMP := "rust-objdump --arch-name=riscv64"
OBJCOPY := "rust-objcopy --binary-architecture=riscv64"

BUILD_PATH := "target/" + TARGET + "/" + MODE + "/"
KERNEL_ELF := BUILD_PATH + "os"
KERNEL_ASM := BUILD_PATH + "os.asm"
KERNEL_BIN := BUILD_PATH + "os.bin"
KERNEL_BIN_LRV := BUILD_PATH + "rcore-n.bin"

clean:
    cargo clean
    cd ../lib_so && cargo clean
    cd ../user && make clean && cd -

unifi-sche:
    cd ../lib_so && make build

user:
    cd ../user && make build

user_lrv:
    cd ../user && make build_lrv

build: user unifi-sche
    cp src/linker-qemu.ld src/linker.ld
    cargo build --features "board_qemu" --release
    {{OBJCOPY}} {{KERNEL_ELF}} --strip-all -O binary {{KERNEL_BIN}}
    rm src/linker.ld

build_lrv: user_lrv
    cp src/linker-lrv.ld src/linker.ld
    cargo build --features "board_lrv" --release
    {{OBJCOPY}} {{KERNEL_ELF}} --strip-all -O binary {{KERNEL_BIN}}
    cp {{KERNEL_BIN}} {{KERNEL_BIN_LRV}}
    rm src/linker.ld

disasm: build
    {{OBJDUMP}} -S -t {{KERNEL_ELF}} > {{KERNEL_ASM}}

disasm_lrv: build_lrv
    {{OBJDUMP}} -S -t {{KERNEL_ELF}} > {{KERNEL_ASM}}

run: build
    {{QEMU}} -machine virt -smp 4 {{SERIAL_FLAGS}} -nographic -bios ./rustsbi-qemu.bin -device loader,file={{KERNEL_BIN}},addr=0x80200000 \
    -device virtio-net-device,netdev=net0 \
    -netdev user,id=net0,hostfwd=tcp::6201-:80

debug_qemu: build
    {{QEMU}} -machine virt -smp 4 {{SERIAL_FLAGS}} -nographic -bios ./rustsbi-qemu.bin -device loader,file={{KERNEL_BIN}},addr=0x80200000 -d int -D debug.log

debug: build disasm
    tmux new-session -d "{{QEMU}} -machine virt -smp 4 {{SERIAL_FLAGS}} -nographic -bios ./rustsbi-qemu.bin -device loader,file={{KERNEL_BIN}},addr=0x80200000 -s -S" && tmux split-window -h "riscv64-unknown-elf-gdb -ex 'file {{KERNEL_ELF}}' -ex 'set arch riscv:rv64' -ex 'target remote localhost:1234'" && tmux -2 attach-session -d

debug_all: build disasm
    tmux new-session -d "{{QEMU}} -machine virt -smp 4 {{SERIAL_FLAGS}} -nographic -bios ./rustsbi-qemu.bin -device loader,file={{KERNEL_BIN}},addr=0x80200000 -d int -D debug.log -s -S" && tmux split-window -h "riscv64-unknown-elf-gdb -ex 'file {{KERNEL_ELF}}' -ex 'set arch riscv:rv64' -ex 'target remote localhost:1234'" && tmux -2 attach-session -d
